package com.meitianhui.convenitenbuy.module.store.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.module.store.contract.OneLotteryYYYContract;
import com.meitianhui.convenitenbuy.module.store.di.DaggerStoreComponent;
import com.meitianhui.convenitenbuy.module.store.di.StoreModule;
import com.meitianhui.convenitenbuy.module.store.model.PayInfoBean;
import com.meitianhui.convenitenbuy.module.store.model.StoreOneLotteryBean;
import com.meitianhui.convenitenbuy.module.store.model.YYYLuckBean;
import com.meitianhui.convenitenbuy.module.store.presenter.OneLotteryYYYPresenter;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.NetworkUtils;
import com.meitianhui.convenitenbuy.util.RxTimerUtils;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.ShakeListener;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.widget.dialog.SettingStoreDialog;

import java.util.List;

import javax.inject.Inject;

/**
 * Created by Administrator on 2017/11/24.
 * 一元抽奖之摇一摇
 */

public class OneLotteryYYYActivity extends BaseToolbarActivity implements OneLotteryYYYContract.View {
    private String mStoreId, mStoreName;

    @Inject
    OneLotteryYYYPresenter presenter;
    private StoreOneLotteryBean.ActivityListEntity entity;
    private PayInfoBean bean;
    private ImageView ivHand;
    private ImageView ivShopCar;
    private ImageView ivCollect;
    private TextView tvStoreName;
    private ImageView ivGoods;
    private TextView tvGoodsName;
    private TextView tvGoodsType;
    private TextView tvLuckTxt;
    private boolean iscondet;//是否从店铺详情进来
    private String url;
    private Vibrator mVibrator;
    private ShakeListener mShakeListener;
    private YYYLuckBean mLuckBean;
    private boolean isVibrating = false;
    private Dialog dialog;
    private AnimationDrawable mBackAnimation;
    private RxTimerUtils rxTimerUtils;
    private RxTimerUtils.IRxNext iRxNext;
    private int shakeNum = 0;//摇奖次数
    private SettingStoreDialog storeDialog;


    @Override
    protected int setView() {
        return R.layout.activity_one_lottery_yyy;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerStoreComponent
                .builder()
                .appComponent(App.getInstance().getAppComponent())
                .storeModule(new StoreModule(this))
                .build()
                .inject(this);
        rxTimerUtils = new RxTimerUtils();
        isEnable(false);
        initId();
        initData();
        initInfo();
        initEvent();
    }

    private void initId() {
        ivHand = getViewById(R.id.yyy_img);
        ivShopCar = getViewById(R.id.yyy_shopcar);
        ivCollect = getViewById(R.id.yyy_collect);
        tvStoreName = getViewById(R.id.yyy_storename);
        ivGoods = getViewById(R.id.yyy_goodsimg);
        tvGoodsName = getViewById(R.id.yyy_goodsname);
        tvGoodsType = getViewById(R.id.yyy_goodstype);
        tvLuckTxt = getViewById(R.id.yyy_luck_tv);
        mBackAnimation = (AnimationDrawable) ivHand.getDrawable();
    }

    private void initInfo() {
        presenter.getYYYLuckData(entity, bean);
    }

    private void initData() {
        setTbTitle(getString(R.string.home_one_lottery_participate_type1));
        Intent intent = getIntent();
        iscondet = intent.getBooleanExtra("iscondet", false);
        if (iscondet) {
            ivShopCar.setVisibility(View.GONE);
            ivCollect.setVisibility(View.GONE);
        }
        entity = intent.getParcelableExtra(Constants.ARGUMENT);
        bean = intent.getParcelableExtra("payInfo");
        url = intent.getStringExtra("url");
        mStoreName = intent.getStringExtra("store_name");
        mStoreId = intent.getStringExtra("store_Id");
        tvStoreName.setText(mStoreName);
        GlideUtils.setRectImage(this,url, R.mipmap.icon_default_app, R.mipmap.icon_default_app, ivGoods);
        tvGoodsName.setText(entity.getTitle());
        tvGoodsType.setText(entity.getAward_name());
        RxUtils.bindEvents(ivCollect, this);
        RxUtils.bindEvents(ivShopCar, this);
    }

    private void initEvent() {
        mVibrator = (Vibrator) getApplication().getSystemService(VIBRATOR_SERVICE);
        mShakeListener = new ShakeListener(this);
        mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
            public void onShake() {
                if (!NetworkUtils.isNetworkConnected(OneLotteryYYYActivity.this)) {
                    TipUtils.showToast(OneLotteryYYYActivity.this, getString(R.string.home_one_lottery_yyy_no_net));
                    return;
                }
                if (mLuckBean == null) {
                    TipUtils.showToast(OneLotteryYYYActivity.this, getString(R.string.home_one_lottery_yyy_error));
                    initInfo();
                    return;
                }
                if (!isVibrating && mLuckBean.getDraw_code_list().size() > 0) {

                    isVibrating = true;
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    //开始 摇一摇手掌动画
                    ivHand.post(new Runnable() {
                        @Override
                        public void run() {
                            mBackAnimation.start();
                        }
                    });
                    startVibrato(); //开始 震动
                    rxTimerUtils.timer(1800, iRxNext);
                }
            }
        });

        iRxNext = new RxTimerUtils.IRxNext() {
            @Override
            public void doNext(long number) {
                if (mBackAnimation != null) {
                    mBackAnimation.stop();
                }
                java.util.Random random = new java.util.Random();// 定义随机类
                List<String> draw_code_list = mLuckBean.getDraw_code_list();

                int lucknum = random.nextInt(draw_code_list.size());// 返回[0,10)集合中的整数，注意不包括10
                String draw = draw_code_list.get(lucknum);
                LogUtils.d("mylog", shakeNum + "摇到的随机数" + lucknum + " 数组的数" + draw + " 中奖" + mLuckBean.getLuck_code());
                if (shakeNum == 12) {
                    setDialog(3, draw);
                    return;
                }
                if (mLuckBean.getLuck_code().equals(draw)) {
                    setDialog(1, draw);
                    presenter.postLuckMsg(mLuckBean);
                } else {
                    isVibrating = false;
                    shakeNum++;//剩余次数加1
                    setDialog(2, draw);

                }

            }
        };
    }

    public void setDialog(final int isluck, final String draw) {
        dialog = new Dialog(this, R.style.dialog_custom);
        dialog.setContentView(R.layout.dialog_yyy);
        if (isluck == 1) {
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
        } else if (isluck == 2) {
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
        } else if (isluck == 3) {
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
        }
        dialog.show();

        ImageView dialog_img_bg = (ImageView) dialog.findViewById(R.id.dia_yyy_bg);
        RelativeLayout dialog_rlat = (RelativeLayout) dialog.findViewById(R.id.dia_yyy_bg_relat);
        if (draw.equals("0")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_1);
        } else if (draw.equals("1")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_2);
        } else if (draw.equals("2")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_3);
        } else if (draw.equals("3")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_4);
        } else if (draw.equals("4")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_5);
        } else if (draw.equals("5")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_6);
        } else if (draw.equals("6")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_7);
        } else if (draw.equals("7")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_8);
        } else if (draw.equals("8")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_9);
        } else if (draw.equals("9")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_10);
        } else if (draw.equals("10")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_11);
        } else if (draw.equals("11")) {
            dialog_img_bg.setImageResource(R.mipmap.one_lottery_yyy_animal_12);
        }


        TextView dialog_tv = (TextView) dialog.findViewById(R.id.dia_yyy_tv);
        TextView dialog_chcek = (TextView) dialog.findViewById(R.id.dia_yyy_check);
        dialog_chcek.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(OneLotteryYYYActivity.this, OneLotteryParticipateActivity.class);
                startActivity(it);
                finish();
            }
        });
        if (isluck == 1) {
            dialog_tv.setText(getString(R.string.home_one_lottery_yyy_congratulation));
            dialog_chcek.setVisibility(View.VISIBLE);
        } else if (isluck == 2) {
            dialog_tv.setText(getString(R.string.home_one_lottery_yyy_try));
            dialog_chcek.setVisibility(View.GONE);
        } else if (isluck == 3) {
            dialog_tv.setText(getString(R.string.home_one_lottery_yyy_end));
            dialog_chcek.setVisibility(View.GONE);
            dialog_rlat.setVisibility(View.GONE);
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (isluck == 1) {
                    Intent it = new Intent(OneLotteryYYYActivity.this, OneLotteryParticipateActivity.class);
                    startActivity(it);
                    finish();
                } else if (isluck == 3) {
                    finish();
                }
            }
        });

    }

    public void startVibrato() {
        //定义震动
        mVibrator.vibrate(new long[]{500, 200, 500, 200}, -1); //第一个｛｝里面是节奏数组， 第二个参数是重复次数，-1为不重复，非-1俄日从pattern的指定下标开始重复
    }

    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.yyy_collect:
                presenter.postFavoriteStore(mStoreId);
                break;
            case R.id.yyy_shopcar:
                Intent intent = new Intent(OneLotteryYYYActivity.this, StoreDetailActivity.class);
                intent.putExtra("store_id", mStoreId);
                startActivity(intent);
                break;

        }
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    protected void clickBack() {
        showReturnDialog();
    }


    @Override
    public void onBackPressed() {
        showReturnDialog();
    }

    private void showReturnDialog() {
        storeDialog = new SettingStoreDialog(OneLotteryYYYActivity.this, new SettingStoreDialog.AlertDialogListener() {
            @Override
            public void onConfirmClick() {
                storeDialog.dismiss();
                finish();
            }

            @Override
            public void onCancelClick() {
                storeDialog.dismiss();
            }
        });
        storeDialog.show();
        storeDialog.setDialogTitle("提示");
        storeDialog.setDialogContent("确定不玩了吗？");
    }

    @Override
    public void getYYYLuckDataBack(boolean result, String msg, YYYLuckBean bean) {
        mLuckBean = bean;
        if (result) {
            setTextAnimal(mLuckBean.getLuck_code());
        } else {
            TipUtils.showToast(App.getInstance(), msg);
        }
    }

    @Override
    public void postLuckMsgBack(boolean result, String msg) {
        if (!result) {
            TipUtils.showToast(App.getInstance(), msg);
        }
    }

    @Override
    public void postFavoriteStoreBack(boolean result, String msg) {
        if (result) {
            TipUtils.showToast(App.getInstance(), getString(R.string.home_one_lottery_yyy_favorite_success), 1);
        }
    }

    private void setTextAnimal(String code) {
        if (code.equals("0")) {
            tvLuckTxt.setText("鼠");
        } else if (code.equals("1")) {
            tvLuckTxt.setText("牛");
        } else if (code.equals("2")) {
            tvLuckTxt.setText("虎");
        } else if (code.equals("3")) {
            tvLuckTxt.setText("兔");
        } else if (code.equals("4")) {
            tvLuckTxt.setText("龙");
        } else if (code.equals("5")) {
            tvLuckTxt.setText("蛇");
        } else if (code.equals("6")) {
            tvLuckTxt.setText("马");
        } else if (code.equals("7")) {
            tvLuckTxt.setText("羊");
        } else if (code.equals("8")) {
            tvLuckTxt.setText("猴");
        } else if (code.equals("9")) {
            tvLuckTxt.setText("鸡");
        } else if (code.equals("10")) {
            tvLuckTxt.setText("狗");
        } else if (code.equals("11")) {
            tvLuckTxt.setText("猪");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rxTimerUtils.cancel();
        if (mBackAnimation != null) {
            mBackAnimation.stop();
        }
        mShakeListener.stop();
    }
}
